package com.wujunshen.orika.convert;

import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MappingContext;
import ma.glasnost.orika.converter.BidirectionalConverter;
import ma.glasnost.orika.metadata.Type;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * User:  FrankWoo(吴峻申) <br>
 * Date:  2018/8/13 <br>
 * Time:  16:04 <br>
 * Email: frank_wjs@hotmail.com <br>
 */
@Slf4j
public class DateConverter extends BidirectionalConverter<Date, String> {
    private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    @Override
    public String convertTo(Date source, Type<String> destinationType, MappingContext mappingContext) {
        return DateFormatUtils.format(source, DATE_FORMAT);
    }

    @Override
    public Date convertFrom(String source, Type<Date> destinationType, MappingContext mappingContext) {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        try {
            return sdf.parse(source);
        } catch (ParseException e) {
            log.error("exception message is:{}", ExceptionUtils.getStackTrace(e));
        }
        return null;
    }
}